import type { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/stores";
import type { RolesPerms } from "@/api/auth/types";

import { dynamicRoutes } from "@/settings";

/** 过滤动态路由. */
const filterDynamicRoutes = (rolesPerms: RolesPerms, routes: RouteRecordRaw[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((oldRoute) => {
    const route: RouteRecordRaw = { ...oldRoute };
    route.meta = { ...oldRoute.meta };
    //包含孩子组件,添加目录.
    if (oldRoute.children) {
      route.children = filterDynamicRoutes(rolesPerms, oldRoute.children);
    }
    if (route.meta && route.meta.roleCode) {
      if (
        rolesPerms.roleCodes.length > 0 &&
        rolesPerms.roleCodes.includes(route.meta.roleCode as string)
      ) {
        asyncRoutes.push(route);
      } else {
        console.log("403", route.path + "要求角色：" + route.meta.roleCode);
      }
    } else if (route.meta && route.meta.permCode) {
      if (
        rolesPerms.permCodes.length > 0 &&
        (rolesPerms.permCodes.includes("*") ||
          rolesPerms.permCodes.includes(route.meta.permCode as string))
      ) {
        asyncRoutes.push(route);
      } else {
        console.log("403", route.path + "要求权限：" + route.meta.permCode);
      }
    } else {
      asyncRoutes.push(route);
    }
  });
  return asyncRoutes;
};

// setup
export const usePermissionStore: any = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(rolesPerms: RolesPerms) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 根据角色和权限过滤动态路由
      const accessedRoutes = filterDynamicRoutes(rolesPerms, dynamicRoutes);
      setRoutes(accessedRoutes);
      resolve(accessedRoutes);
    });
  }

  return {
    routes,
    setRoutes,
    generateRoutes
  };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
